<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Minutes</title>
    <link rel="stylesheet" type="text/css" href="styles/outliner.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="styles/meeting.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="styles/pepper-grinder/jquery-ui-1.8.5.custom.css" media="screen" />
    <style type="text/css">@import "styles/jquery.countdown.css";</style>
    <script type="text/javascript" src="scripts/jquery-1.4.2.min.js" ></script>
    <script type="text/javascript" src="scripts/underscore-min.js"></script>
    <script type="text/javascript" src="scripts/jquery-ui-1.8.5.custom.min.js"></script>
    <script type="text/javascript" src="scripts/jquery.layout.min-1.2.0.js"></script>
    <script type="text/javascript" src="scripts/shortcuts.js"></script>
    <script type="text/javascript" src="scripts/jquery.qtip-1.0.0-rc3.min.js"></script>
    <script type="text/javascript" src="scripts/couch.js"></script>
    <script type="text/javascript" src="scripts/jquery.couch.js"></script>
    <script type="text/javascript" src="scripts/jquery.parsequery.js"></script>
    <script type="text/javascript" src="scripts/wikid-0.2.js" ></script>
    <script type="text/javascript" src="scripts/date.js" ></script>
    <script type="text/javascript" src="scripts/meeting.js" ></script>
    <script type="text/javascript" src="scripts/lineShark.js" ></script>
    <script type="text/javascript" src="scripts/jquery.countdown.js" ></script>
    <script type="text/javascript" src="scripts/jquery.scrollTo.min.js" ></script>
    <script type="text/javascript" src="scripts/Person/Person.js" ></script>
    <script type="text/javascript" src="scripts/jquery.md5.js"></script>
    <script type="text/javascript">

        $(function() {

            var db_name = wikid.parseDBname(window.location);
            var db = new CouchDB(db_name);
            var wikid_id = wikid.parseTopicName(window.location);
            var doc = db.open(wikid_id);
            var readableId = wikid.titleFromTopicId(wikid_id);

            if (!doc) {
                window.location = "startMeeting.html";
                return;
            }
            $('.readableId').text(readableId);
            document.title = 'Minutes - ' + readableId;
            




            //auto save on close
            var saved = false;
            $(window).bind('unload', function() {
                //if(!confirm("Please save page")) {
                //    return false;
                //}
            });

            // set the layout manager
            $('body').layout({
                applyDefaultStyles: true,
                enableCursorHotkey: false
            });




            /*********************************************************************
             * Bind attendee buttons
             */


            $(".attendee").each(function(i, item){
                var index = i + 1;
                var keycombo = 'alt+' + index;
                 shortcut.add(keycombo, function() {
                    attendeeTalking($('.attendee-' + index));
                });
            }).click(function(){attendeeTalking($(this))});




            var minutes = $('<div id="'+ wikid_id +'"></div>');
            $('.ui-layout-center').append(minutes)
            var conversationTags = wikid.findConversationTags(wikid_id,db).rows;
            meeting.ui.createMeeting(minutes, conversationTags, db, wikid_id);

            /**
             * Agenda
             */
            if (doc['-agenda']) {
                var agenda = meeting.agendaItemsToHTML(doc['-agenda']);
                $('#agendaHolder').append(agenda);
            }
            if (doc['-attendees']) {
                meeting.attendeesToHtml(doc['-attendees'], db, $('#attendees'));
            } else {
                doc['-attendees'] = [];
            }

            $("#agenda span.agendaItem").hover(
                function() {
                    $(this).addClass('ui-state-focus');
                }, function() {
                    $(this).removeClass('ui-state-focus');
                }
            ).click(function() {
                $('.currentAgenda').removeClass('ui-state-focus').removeClass("currentAgenda").addClass("coveredAgenda");
                var minute_image = $(this).addClass("currentAgenda").data('minute');
                var minute = $.extend(true, {}, minute_image  );
                minute._id = _.uniqueId(minute._id);


                // find the matching topic stack
                // requested topic stack
                if (!minute.topicStack || minute.topicStack.length == 0) {
                    meeting.ui.currentDiv = meeting.ui.mainPanel;
                    lineShark.addContext(minute, meeting.ui.context);
                    minute.topicStack = [];
                    meeting.ui.context.topicStack = [];
                    meeting.ui.addMinute(minute);

                } else {
                    // there is a topic stack. Find the closest, or create a new one
                    var best = null;
                    $.each(minute.topicStack, function(i, stackItem) {
                        var compareStackItem = meeting.ui.context.topicStack[i];
                        if ( compareStackItem == stackItem) best = i;
                    });
                    if (best == null) {
                        // start at the root and rebuild the stack
                        meeting.ui.currentDiv = meeting.ui.mainPanel;
                        meeting.ui.context.topicStack = [];
                        $.each(minute.topicStack, function(i, stackItem) {
                            var tree_minute = lineShark.eatLine('#' + stackItem, meeting.ui.context);
                            tree_minute._id =  _.uniqueId('etest-');
                            meeting.ui.addMinute(tree_minute);
                            lineShark.addContext(minute, meeting.ui.context);
                            meeting.ui.addMinute(minute);
                        });

                    } else {

                        var parents = [meeting.ui.currentDiv];

                        // use the div at this part of the stack
                        meeting.ui.currentDiv.parents('.topicBox').each(function(i, cur){
                            parents.push(cur);
                        });
                        parents.reverse();
                        var div = $(parents[best]);
                        meeting.ui.currentDiv = div;
                        meeting.ui.context.topicStack = minute.topicStack;
                        meeting.ui.addMinute(minute);
                    }
                }

            });

            $('#attendeeName').autocomplete({
                delay: 250,
                source: function(request, response) {
                    var term = request.term;
                    var matches = db.view("system/doc_by_tag", {
                        key : 'Person',
                        startkey_docid: term,
                        endkey_docid: term + 'zzz',
                        limit: 10
                    });
                    response(_.map(matches.rows, function(row) { return  row.id }));
                },
                open: function(event, ui) {
                    $('#newAttendee').hide();
                }
            }).bind('autocompleteclose keyup', function(e) {
                //console.log(e);
                if (e && (e.keyCode != 13 && e.keyCode != 0))  return;


                var personID = $.trim($(this).val());
                if (!personID || '' == personID) return;
                var personDoc = db.open(personID);
                if (!personDoc) {
                    createNewAttendee();

                    return;
                };
                if (!personDoc['-tags'] || !_.include(personDoc['-tags'] , 'Person')) return;
                if (_.contains(doc['-attendees'],personID)) return;
                doc['-attendees'].push(personID);
                // save the doc
                db.save(doc);

                var toAdd = meeting.attendeeToHtml(personID, personDoc);
                $('#attendees').append(toAdd)
                $(this).val('').focus();
            });

            $('#newAttendee').hide();
            $('#cancelNewAttendee').button().click(function() {
                $('#newAttendee').hide();
                $('#attendeeName').focus();
            });
            $('#addNewAttendee').button().click(function() {
                // create the person
                var first = $('#firstName').val();
                var last  = $('#lastName').val();
                var email = $('#email').val();
                var title = first + '_' + last;
                var now = new Date();

                var Person = {
                    first: first,
                    lastName: last
                };
                if (email) {
                    Person.email = email;
                }

                var p_doc = {
                    _id: title,
                    '-tags': ['Person'],
                    '-lastmodified' : iso8601(now),
                    Person : Person
                }
                db.save(p_doc);
                doc['-attendees'].push(title);
                // save the doc
                db.save(doc);
                var toAdd = meeting.attendeeToHtml(title, doc);
                $('#attendees').append(toAdd)
                $('#newAttendee').hide();
                $('#attendeeName').focus();
            });


            // a bit of adjustment on the center pane
            $('.ui-layout-center').css('padding-left', '15px');

            //maybe later. A way to lasso past text and put in a topic 
            //$('.ui-layout-center').selectable({tolerance: 'fit'});

            // check the status of recording
            $.getJSON('http://localhost:5987/json/record/status?callback=?',  function(data,status) {
                if (!data) cantDetermineRecordingStatus();
                if(data.status == "stopped") {
                    $.getJSON('http://localhost:5987/json/record/start?callback=?', {'id' : wikid_id}, recordingStatusChanged);
                } else  {
                    var recording_id = data.recording_id;
                    if (recording_id == wikid_id) alreadyRecordingThisMeeting();
                    else anotherMeetingIsCurrentlyRecorded();
                }

            });
            // start the recording!!!
            function recordingStatusChanged(data, status) {
                //console.log('post returend ');
                if (data.status == "failed") {
                    alert('unable to start recording');
                }
                if (data.status == "already_recording") {
                    alert('Something is already recording');
                }
                if (data.status == "recording") {
                    data.recording_id;
                    data.timestamp;
                    var result = meeting.toMeeting(doc, db);
                    $('#dateTime').text(result.readableStartDate);
                    $('#duration').countdown({
                        since: result.startDate,
                        compact: true,
                        format: 'HMS',
                        description: ''
                    });
                }
                if (data.status == "stopped") {

                }
            }
            /**
             * Record Button
             */
            $('#recordButton').button().click(function(){
                 $(this).button('disable');
                 $.getJSON('http://localhost:5987/json/record/stop?callback=?', {}, function recordingStatusChanged(data, status){
                     var recordingDuration = data.duration;
                     // reload in-case of changes
                     doc = db.open(wikid_id);
                     var result = meeting.toMeeting(doc, db);
                     $('#duration').countdown('pause');

                     doc['-Recording'] = {
                         startDate : result.startDate,
                         '-duration' : recordingDuration,
                         '-media' : {
                             recording1: {
                                  startDate : result.startDate,
                                  'duration' : recordingDuration
                             }
                         }
                     };
                     var now = new Date();
					 doc["-lastmodified"] = iso8601(now);
                     db.save(doc);

                 });
            });

        });

        function anotherMeetingIsCurrentlyRecorded() {
            alert('Another meeting is already being recorded');
        }

        function alreadyRecordingThisMeeting() {
            alert('This meeting is already being recorded');
        }

        function cantDetermineRecordingStatus() {
            alert('cant determine recording status');
        }


        function createNewAttendee() {
            $('#newAttendee').show().addClass('ui-state-highlight');
            $('#newAttendee button').removeClass('ui-state-focus');
            var full = $('#attendeeName').val();
            $('#attendeeName').val('');
            var divided = full.split(/[\s_]/g);
            var first;
            var last;
            if (_.isArray(divided) && divided.length > 1) {
                first = _.first(divided, divided.length -1).join(' ');
                last = _.last(divided);
            } else {
                first = full;
                last = '';
            }

            $('#firstName').val(first);
            $('#lastName').val(last);
            $('#email').val('');
            if (!last || last == '') {
                $('#lastName').focus();
            } else {
                $('#email').focus();
            }



        }



        function attendeeTalking(attendeeDiv){
            var topic_id = attendeeDiv.attr('title');
            var name = attendeeDiv.find('p').text();
            var when = new Date();
            var current = $('.current');
            var parent = current.parent();
            var newNote = $('<li><span class="talk">' + name + ' is talking.</span></li>');
            $('.current').replaceWith(newNote);
            //newNote.fadeIn(1500);
            newNote.effect("highlight", {}, 3000);
            parent.append(current);
            $("#entry").focus();
            var item = newNote.children('.talk');
            item.data('info', {date: when, who: topic_id});
            item.qtip({
                content: {
                    text: item.data('info').date + 'daddas'
                },
                style: {
                    name: 'cream',
                    tip: true,
                    border: {
                        width:5,
                        radius: 10
                    }
                },
                 position: {
                      corner: {
                         target: 'topLeft',
                         tooltip: 'bottomLeft'
                      }
                   }
            });



            



        }


        function highlightAttendee(number) {
            $('.attendee-' + number).effect("highlight", {}, 500);
        }



        function appendNote(note, clearEntry) {
            var when = new Date();
            var current = $('.current');
            var parent = current.parent();
            var newNote = $('<li><span class="item">' + note + '</span></li>');
            $('.current').replaceWith(newNote);
            //newNote.fadeIn(1500);
            newNote.effect("highlight", {}, 3000);
            parent.append(current);
            $("#entry").focus();
            var item = newNote.children('.item');
            item.data('info', {date: when});
            item.qtip({
                content: {
                    text: item.data('info').date + 'daddas'
                },
                style: {
                    name: 'cream',
                    tip: true,
                    border: {
                        width:5,
                        radius: 10
                    }
                },
                 position: {
                      corner: {
                         target: 'topLeft',
                         tooltip: 'bottomLeft'
                      }
                   }
            });
        }



    </script>

</head>
<body>
    <div class="ui-layout-north">


        <div id="recordDiv">
            <button id="recordButton" >Stop</Button>
        </div>
        <div id="subInfo">

            <div id="duration">00:23:01</div>
            <div id="dateTime">12 August 2010, 10:02am</div>
        </div>
        <div id="mainTopic" class="readableId">Meeting With Randy</div>
    </div>
    <div id="agenda" class="ui-layout-west">
        <div class="ui-widget-header">Agenda</div>
        <div id="agendaHolder" class="ui-widget-context">

        </div>
        <div class="ui-widget-header">Types</div>
        <div class="ui-widget-context">
            <div class="attendee" title="Actionable">
                <img src="images/actionable/korganizer_todo.64.png" alt="An action that needs to be done after the meeting." title="An action that needs to be done after the meeting."/>
                <p>Action</p>
            </div>
            <div class="attendee" title="Question">
                <img src="images/question/filetypes.64.png" alt="A question that needs to be answered after the meeting" title="A question that needs to be answered after the meeting"/>
                <p>Question</p>
            </div>
            <div class="attendee" title="FutureItem">
                <img src="images/future-idea/ktip.64.png" alt="A future item/Idea" title="A future item/Idea"/>
                <p>Future Item/Idea</p>
            </div>
        </div>
    </div>
    <div class="ui-layout-east">
        <div class="ui-widget-header">Attendees</div>
        <div id="attendees">

        </div>
        <div id="newAttendee">
                Person not found. Create?
                <div class="newAttendeeDetails">
                    <div class="fieldHeader">First Name</div>
                    <input type="text" id="firstName" tabindex="3">
                </div>
                <div>
                    <div class="fieldHeader">Last Name</div>
                    <input type="text" id="lastName" tabindex="4">
                </div>
                <div>
                    <div class="fieldHeader">Email</div>
                    <input type="text" id="email" tabindex="5">
                </div>
                <button id="addNewAttendee" tabindex="6">Create</button>
                <button id="cancelNewAttendee" tabindex="7">Cancel</button>
            </div>
        <div class="addAttendeeSection">
            <b>Add Attendee</b><br/>
            <input type="text" id="attendeeName" tabindex="2"/>

        </div>
    </div>
    <div class="ui-layout-center">



    </div>
</body>
</html>